﻿#include "digitalarchivefrm.h"
#include "ui_digitalarchivefrm.h"

#include <QMessageBox>
#include "digitalarchives/cadre.h"
#include "digitalarchives/exporterDlg.h"
#include <QSqlQuery>
#include <QDebug>
#include <QCompleter>
#include <QFileDialog>
#include <QStringList>
#include <QList>
#include <QListWidgetItem>
#include <QPushButton>
#include <QImageReader>
#include <QWidget>
#include <QPrinter>

DigitalArchiveFrm::DigitalArchiveFrm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DigitalArchiveFrm)
{
    ui->setupUi(this);
    setWindowState(Qt::WindowMaximized);

//    ui->centralWidget->setMaximumSize(this->width(), this->height());

    ui->splitter->setStretchFactor(0, 2);
    ui->splitter->setStretchFactor(2, 3);
    ui->splitter->setStretchFactor(3, 8);

    ui->splitter_2->setStretchFactor(0, 1);
    ui->splitter_2->setStretchFactor(1, 8);


    this->image = new QImage();

    //图片列表点击事件信号槽
//    ui->listWidget->setEditTriggers(QListWidget::AnyKeyPressed);
//    ui->listWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
//    connect(ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem * )), this,
//            SLOT(OnItemDoubleClicked(QListWidgetItem * )));

    cadre = new CCadre();
    connect(cadre, SIGNAL(sendSignal(QString, QString)), this, SLOT(reshow(QString, QString)));
    ui->tabWidget_2->setCurrentIndex(0);

    ui->graphic_show->setMouseTracking(true);
    ui->graphic_show->installEventFilter(this);
    scene = new QGraphicsScene(-300, -200, 600, 200); //创建QGraphicsScene

    ui->graphicsView->setScene(scene); //与view关联
    ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);

    ui->graphicsView->setCursor(Qt::CrossCursor); //设置鼠标
    ui->graphicsView->setMouseTracking(true); //
    ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);

    connect(ui->graphicsView, SIGNAL(mouseMovePoint(QPoint)),
                     this, SLOT(on_mouseMovePoint(QPoint)));

    connect(ui->graphicsView, SIGNAL(mouseClicked(QPoint)),
                     this, SLOT(on_mouseClicked(QPoint)));
    connect(ui->graphicsView, SIGNAL(mouseReleased(QPoint)),
                     this, SLOT(on_mouseReleased(QPoint)));


    //邦定数据源

    QStringList strings;


    QSqlQuery db_query("SELECT ClassName  FROM ArchiveClassCode ");
    while (db_query.next()) {
        QString lx_name = db_query.value(0).toString();
        strings.append(lx_name);
    }
    QSqlTableModel *model = new QSqlTableModel();
    model->setTable("ArchiveClassCode");
    model->select();
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->removeColumn(2);
    model->removeColumn(0);
    model->setHeaderData(0, Qt::Horizontal, "档案类别");
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);


}

DigitalArchiveFrm::~DigitalArchiveFrm()
{
    delete ui;
}


void DigitalArchiveFrm::on_btn_showdir_clicked()
{
    //档案查阅界面初始化
    //widget初始化
    ui->treeWidget->clear();                             //清空内容
    ui->treeWidget->headerItem()->setText(0, "档案类别");  //设置字段，类别名词
    departTree("", ui->treeWidget);
}

//树节点建立
void DigitalArchiveFrm::departTree(QString root, QTreeWidget *tree) {

    QSqlQuery query(
            "select ClassName,ClassNum from ArchiveClassCode where ClassNum in (select ClassNum from ArchiveDirectoryInfo where IDNum = '" +
            cadre_id + "')");
    qDebug() <<
             "select ClassName,ClassNum from ArchiveClassCode where ClassNum in (select ClassNum from ArchiveDirectoryInfo where IDNum = '" +
             cadre_id + "')";
    while (query.next()) {
        QString cadre_type = query.value(0).toString();
        QString arc_id = query.value(1).toString();
        QTreeWidgetItem *item =
                new QTreeWidgetItem(tree, QStringList(QString(cadre_type)));
        /*创建ITEM,由于是最高类别，插入对象为TreeWidget*/
        if (!cadre_type.isEmpty()) {
            departTree(arc_id, item);    //开启递归
        }
    }
}

//树子节点建立
void DigitalArchiveFrm::departTree(QString root, QTreeWidgetItem *item) {
    cadrename = ui->lineedit_name->text();
    QSqlQuery query(
            "select PageNum from ArchiveDirectoryInfo where  ClassNum= '" + root + "' and IDNum =  '" + cadre_id + "' ");        //设置查询语句
    qDebug() << "select PageNum from ArchiveDirectoryInfo where  ClassNum= '" + root + "' and IDNum =  '" + cadre_id +
                "' ";

    while (query.next()) {
        QString page = query.value(0).toString(); //档案页数
        for (int i = 1; i <= page.toInt(); i++) {
            QTreeWidgetItem *items =
                    new QTreeWidgetItem(item, QStringList(QString(i)));
            /*创建新的ITEM,插入到ITEM中，设置名称为页数*/
            QString item_text = "第" + QString::number(i) + "页";
            items->setText(0, item_text);
        }
    }
}

void DigitalArchiveFrm::on_mouseMovePoint(QPoint point)
{//鼠标移动事件，point是 GraphicsView的坐标,物理坐标

//    qDebug()<<point.x()<<point.y();
    x_start= point.x();
    y_start = point.y();
    QPointF pointScene=ui->graphicsView->mapToScene(point); //转换到Scene坐标
//    qDebug()<<("Scene 坐标：%.0f,%.0f",pointScene.x(),pointScene.y());
}

void DigitalArchiveFrm::on_mouseClicked(QPoint point)
{//鼠标单击事件
    x_start= point.x();
    y_start = point.y();
    qDebug()<<point.x()<<point.y();
    pointScene_start=ui->graphicsView->mapToScene(point); //转换到Scene坐标

}

void DigitalArchiveFrm::on_mouseReleased(QPoint point)
{//鼠标单击事件
    qDebug()<<point.x()<<point.y();
    x_end= point.x();
    y_end = point.y();
    qDebug()<<point.x()<<point.y();
    pointScene_start=ui->graphicsView->mapToScene(point); //转换到Scene坐标
}

void DigitalArchiveFrm::on_btn_screenshot_clicked()
{
    //    截图区域的宽和高
        int height = y_end - y_start;
        int width = x_end - x_start;
        QSize captureSize(width, height);


        QImage image(fileName);
        QSize ImgSize(image.width(), image.height());
        qDebug() << "宽为：" << width << "高为：" << height;
        img_opt = capture(x_start, y_start, captureSize, ImgSize, fileName);

        img_save = QPixmap::fromImage(img_opt);

        qDebug() << img_opt.byteCount();
        ui->label->setPixmap(img_save.scaled(300,170));
}

//获取档案类别
QString DigitalArchiveFrm::get_archive_type() {
    QString name;
    cadre_name = ui->lineedit_name->text();
    QString id = QString::number(ui->tableView->currentIndex().row() + 1);

    QString sql = "select ClassName from ArchiveClassCode where description = '" + id + "' ";
    qDebug() << sql;
    QSqlQuery query("select ClassName from ArchiveClassCode where description = '" + id + "' ");
    if (query.next()) {
        QSqlRecord idrec = query.record();
        name = idrec.value(0).toString();
        qDebug() << name;
    }
    return name;
}

//截图
QImage DigitalArchiveFrm::capture(int x, int y, QSize captureSize, QSize Imgsize, QString img) {
    QImage image;
    QImageReader reader;
    qDebug()<<img;
    reader.setFileName(img);
    QSize imageSize = reader.size();
    imageSize.scale(Imgsize.width(), Imgsize.height(), Qt::KeepAspectRatio);
    image = reader.read();

    img_opt = image.copy(x, y, captureSize.width(), captureSize.height());

    return img_opt;
}

//图像文件替换事件
void DigitalArchiveFrm::on_btn_change_clicked()
{
    archive_type = get_archive_type();

    QFile file(fileName);
    file.remove();

    bool saveSuccess = img_save.toImage().save(fileName, "PNG", 100);
    if(QFileInfo(fileName).suffix().isEmpty())
        fileName.append(".png");
    if (!saveSuccess) {

        QMessageBox::warning(this, "警告", "替换文件失败",
                             QMessageBox::Ok, QMessageBox::NoButton);
    }
    qDebug() << "成功替换";

    //    替换数据库中图像文件

        ui->listWidget->clear();
        QDir dir;
        dir.setPath(dirpath);
        showDirFile(dir);

}

//插入图像
void DigitalArchiveFrm::on_btn_insert_clicked()
{
    int currow = ui->listWidget->currentIndex().row() + 1;

    QString itemtext=QString::number(currow+1);
    QListWidgetItem *imageItem = new QListWidgetItem(QIcon(img_save.scaled(QSize(100,100))),itemtext);

    ui->listWidget->insertItem(currow, imageItem);
    QString newfile_path = dirpath+"/"+itemtext;
    QFile file(newfile_path);
    if (file.exists())
    {
        QString save_name;
        save_name = QFileDialog::getSaveFileName(this,
                                                 tr("另存为"), "", tr("Config Files (*.png)"));
        qDebug()<<save_name;
        if (!save_name.isNull())
        {
            bool saveSuccess = img_save.toImage().save(save_name,"PNG" , 100);

            qDebug()<<img_save.size();
            if (!saveSuccess) {

                QMessageBox::warning(this, "警告", "保存文件失败",
                                     QMessageBox::Ok, QMessageBox::NoButton);
            }
            else{
                //如果没有写后缀就自动加上
                if(QFileInfo(save_name).suffix().isEmpty())
                    save_name.append(".png");
                qDebug() << "成功保存";
            }

        }
    }
    else{
        bool saveSuccess = img_save.toImage().save(newfile_path,"PNG" , 100);
        qDebug()<<img_save.size();
        if (!saveSuccess) {

            QMessageBox::warning(this, "警告", "保存文件失败",
                                 QMessageBox::Ok, QMessageBox::NoButton);
        }
        qDebug() << "成功保存";
    }



    //ID根据档案目录中的IDNum和档案类别确定
    QString directory_id;

    QSqlQuery query_id(
                "select DirectoryId from ArchiveDirectoryInfo where IDNum = '" + cadre_id + "' and ClassNum = '" +
                QString::number(ui->tableView->currentIndex().row() + 1) + "'");
    //        QString sql = "select DirectoryId from ArchiveDirectoryInfo where IDNum = '" + cadre_id + "' and ClassNum = '" +
    //                      QString::number(ui->tableView->currentIndex().row() + 1) + "'";
    //        qDebug() << sql;
    if (query_id.exec()) {
        QSqlRecord idrec = query_id.record();
        directory_id = idrec.value(0).toString();
    }
    QString path= dirpath +"/"+itemtext;

    QSqlQuery insert_query(
                "insert into ArchiveSave (ArchiveId,ArchivePath,Remark) values ( '" + directory_id + "','" + path +
                "','') ");

    //        QString sql1 =
    //                "insert into ArchiveSave (ArchiveId,ArchivePath,Remark) values ('" + directory_id + "','" + path +
    //                "','','') ";
    //        qDebug() << sql1;


    if (insert_query.exec()) {
        qDebug() << "成功保存至数据库中";
    }
    ui->listWidget->clear();
    QDir dir;
    dir.setPath(dirpath);
    showDirFile(dir);

}

//删除图像
void DigitalArchiveFrm::on_btn_delete_clicked()
{
//    archive_type = get_archive_type();
//    QString page = ui->listWidget->model()->index(ui->listWidget->currentIndex().row(), 0).data().toString().mid(1, 1);
//    QString filename =
//            "/home/sa/" + cadre_name + "/" + archive_type + "/" + cadre_name + "-" + archive_type + "-" + page + ".png";
//    qDebug() << filename << page;
    QFile file(fileName);
    file.remove();
    QListWidgetItem *item = ui->listWidget->takeItem(ui->listWidget->currentRow());
    delete item;

    //    删除数据库中图像文件

        //ID根据档案目录中的IDNum和档案类别确定
        QString archive_id;

        QSqlQuery query_id(
                "select DirectoryId from ArchiveDirectoryInfo where IDNum = '" + cadre_id + "' and ClassNum = '" +
                QString::number(ui->tableView->currentIndex().row() + 1) + "'");
        QString sql = "select DirectoryId from ArchiveDirectoryInfo where IDNum = '" + cadre_id + "' and ClassNum = '" +
                      QString::number(ui->tableView->currentIndex().row() + 1) + "'";
        qDebug() << sql;
        if (query_id.exec()) {
            QSqlRecord idrec = query_id.record();
            archive_id = idrec.value(0).toString();
        }

        QSqlQuery delete_query("delete from ArchiveSave where ArchiveId = '" + archive_id + "' and ArchivePath = '" + fileName + "' ");
        QString sql1 = "delete from ArchiveSave where ArchiveId = '" + archive_id + "' and ArchivePath = '" + fileName + "'";
        qDebug() << sql1;

        if (delete_query.exec()) {
            qDebug() << "成功删除该行数据";
        }
        ui->listWidget->clear();
        QDir dir;
        dir.setPath(dirpath);
        showDirFile(dir);

}

//导入图像
void DigitalArchiveFrm::on_btn_importimg_clicked()
{

    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::ExistingFiles);
    if (dialog.exec())
        {
        QDir dir = dialog.directory();
        qDebug()<<dir;

        ui->listWidget->clear();

        showDirFile(dir);
    }
//    foreach(fileName, fileNames)
//    {


//        QFileInfo fi(fileName);
//        QString name = fi.fileName();
//        //分析文件名
//        QStringList list = name.split("-");
//        QString filetype = list[1];
//        QSqlQuery query("select description from ArchiveClassCode where ClassName = '" + filetype + "'");
//        if (query.exec()) {
//            int row = query.record().value(0).toString().toInt();
//            ui->tableView->selectRow(row);
//        }
////        int row = ui->listWidget->count();
////        ui->listWidget->addItem("第" + filepage + "页");
////        ui->listWidget->setCurrentRow(0);
////        QString filepath = "/home/sa/" + list[0] + "/" + list[0] + list[1] + "-" + filetype + "-" + filepage + ".png";
////        qDebug() << filepath;
////        if (image->load(filepath)) {
////            ImgShow(image);
////        }
//    }
}

//导出图像
void DigitalArchiveFrm::on_btn_exportimg_clicked()
{
    //    获取图像数据
    QString archive_type = get_archive_type();
    //    直接保存图像至指定路径下

    int page = ui->listWidget->currentRow() + 1;
    if (page < 0) {

        return;
    } else {

        QString path = "/home/sa/" + cadre_name + "/" + archive_type + "/" + cadre_name + "-" + archive_type + "-" +
                       QString::number(page) + ".png";
        //文件保存
        scene = ui->graphicsView->scene();
        int height = ui->graphicsView->height();
        int width = ui->graphicsView->width();
        //        scene->setSceneRect(0, 0, 5000, 1000);
        QImage image(width, height, QImage::Format_RGB32);
        QPainter painter(&image);
        scene->render(&painter);   //关键函数
        bool saveSuccess = image.save(path, "PNG", 100);


        if (!saveSuccess) {
            QMessageBox::warning(this, "提示", "导出数据出错",
                                 QMessageBox::Ok, QMessageBox::NoButton);
            return;
        }

    }

    //按类别导出

//    QMessageBox *msgBox = new QMessageBox("数字档案",		///--这里是设置消息框标题
//                                          "是要导出当前干部的全部档案图像还是导出当前类别的档案？\n"
//                                          "按 是 导出全部\n"
//                                          "按 否 导出当前类别",						///--这里是设置消息框显示的内容
//                                          QMessageBox::Critical,							///--这里是在消息框显示的图标
//                                          QMessageBox::Yes | QMessageBox::Default,		///---这里是显示消息框上的按钮情况
//                                          QMessageBox::No | QMessageBox::Escape,	///---这里与 键盘上的 escape 键结合。当用户按下该键，消息框将执行cancel按钮事件
//                                          0);
//    msgBox->show();
//    if(msgBox->exec() == QMessageBox::Yes)//模态调用
//    {
//        qDebug() << " Ok is clicked!";//数据处理
//        for(int type_i=0;type_i<=ui->tableView->model()->rowCount();type_i++)
//        {
//            QString name;
//            QString id = QString::number(ui->tableView->currentIndex().row());
//            qDebug()<<db.open();

//            {
//                db = QSqlDatabase::addDatabase("QMYSQL","selectname");
//                db.setDatabaseName("ZZB");
//                if(QSqlDatabase::contains("qt_sql_default_connection"))
//                    db = QSqlDatabase::database("qt_sql_default_connection");
//                else
//                    db = QSqlDatabase::addDatabase("selectname");

//                if(!db.open())
//                {
//                    QMessageBox::warning(this, "错误", "打开数据库失败",
//                                         QMessageBox::Ok,QMessageBox::NoButton);
//                    return;
//                }
//                QString sql = "select Name from ArchiveClassCode where Remark = '"+ id +"' ";
//                qDebug()<<sql;
//                QSqlQuery query("select Name from ArchiveClassCode where Remark = '"+ id +"' ",db);
//                if(query.next()){
//                    QSqlRecord idrec = query.record();
//                    name = idrec.value(0).toString();
//                    qDebug()<<name;
//                }
//                int page_cnt=ui->listWidget->count() ;
//                if(page_cnt<0){

//                    return;
//                }else{


//                    QString cadre_name = lineedit_name->text();
//                    for(int page=1;page<=page_cnt;page++)
//                    {
//                        qDebug()<<page;

//                        QString path="/home/sa/"+cadre_name+"/"+cadre_name+"-"+page+".png";
//                        qDebug()<<path;
//                        bool saveSuccess = image->save("/home/sa/"+cadre_name+"/"+cadre_name+"-"+page+".png","PNG",100);
//                        qDebug()<<saveSuccess;
//                        if(!saveSuccess){
//                            QMessageBox::warning(this, "提示", "导出数据出错",
//                                                 QMessageBox::Ok,QMessageBox::NoButton);
//                            return;
//                        }
//                    }
//                }
//                db.close();
//                QSqlDatabase::removeDatabase("setup");
//            }
//        }

//    }
//    if(msgBox->exec() == QMessageBox::No)//模态调用
//    {

//        QString name;
//        QString id = QString::number(ui->tableView->currentIndex().row()+1);
//        qDebug()<<db.open();

//        {
//            db = QSqlDatabase::addDatabase("QMYSQL","selectname");
//            db.setDatabaseName("ZZB");
//            if(QSqlDatabase::contains("qt_sql_default_connection"))
//                db = QSqlDatabase::database("qt_sql_default_connection");
//            else
//                db = QSqlDatabase::addDatabase("selectname");

//            if(!db.open())
//            {
//                QMessageBox::warning(this, "错误", "打开数据库失败",
//                                     QMessageBox::Ok,QMessageBox::NoButton);
//                return;
//            }
//            QString sql = "select Name from ArchiveClassCode where Remark = '"+ id +"' ";
//            qDebug()<<sql;
//            QSqlQuery query("select Name from ArchiveClassCode where Remark = '"+ id +"' ",db);
//            if(query.next()){
//                QSqlRecord idrec = query.record();
//                name = idrec.value(0).toString();
//                qDebug()<<name;
//            }
//            int page_cnt=ui->listWidget->count() ;
//            if(page_cnt<0){

//                return;
//            }else{


//                QString cadre_name = lineedit_name->text();
//                for(int page=1;page<=page_cnt;page++)
//                {
//                    qDebug()<<page;

//                    QString path="/home/sa/"+cadre_name+"/"+name+"/"+cadre_name+"-"+name+"-"+QString::number(page)+".png";
//                    qDebug()<<path;
////                    ui->graphicsView->scene();
////                    image= new QImage(width,height,QImage::Format_RGB32);
////                    QPainter painter=new QPainter();
////                    scene->render(&painter);

//                    bool saveSuccess = image->save(path,"PNG",100);
//                    qDebug()<<saveSuccess;
//                    if(!saveSuccess){
//                        QMessageBox::warning(this, "提示", "导出数据出错",
//                                             QMessageBox::Ok,QMessageBox::NoButton);
//                        return;
//                    }
//                }
//            }
//            db.close();
//            QSqlDatabase::removeDatabase("setup");
//        }
//    }
}

//图像显示
void DigitalArchiveFrm::ImgShow(QImage *image) {

    pixmapitem = new QGraphicsPixmapItem(QPixmap::fromImage(*image));
    scene = new QGraphicsScene();
    scene->addItem(pixmapitem);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->show();
}

void DigitalArchiveFrm::on_btn_zoomout_clicked()
{
    num = num * 1.2;
    pixmapitem->setScale(num);
    qDebug("num + :%d", num);
}

void DigitalArchiveFrm::on_btn_rotate_clicked()
{
    pixmapitem->setRotation(90 + pixmapitem->rotation());
}

void DigitalArchiveFrm::on_btn_zoomin_clicked()
{
    num = num * 0.8;
    pixmapitem->setScale(num);
    qDebug("num + :%d", num);
}

void DigitalArchiveFrm::on_btn_cadreselection_clicked()
{
    cadre->show();
}

//页码切换事件
void DigitalArchiveFrm::on_listWidget_itemChanged(QListWidgetItem *item) {
//    ui->listWidget->clear();
//    int item_cnt = ui->listWidget->count();
//    for (int i = 1; i <= item_cnt; i++) {
//        ui->listWidget->addItem("第" + QString::number(i) + "页");
//    }
}

void DigitalArchiveFrm::on_tableView_clicked(const QModelIndex &index) {

    if (ui->lineedit_name->text().size() != 0) {

        //选中某行，选择该干部该档案类别下文件个数
        ui->listWidget->clear();
        cadrename=ui->lineedit_name->text();
        int currow = ui->tableView->currentIndex().row() + 1;
        QSqlQuery query("select ClassName from ArchiveClassCode where description = '" + QString::number(currow) + "'" );
        if (!query.next()) {
            archive_type = query.value(0).toString();
        }
        archive_type = query.value(0).toString();

         QDir dir("/home/sa/" + cadrename + "/" + archive_type);
         dirpath=dir.absolutePath();
//        qDebug()<<dir;

        showDirFile(dir);
    }
}

void DigitalArchiveFrm::showDirFile(QDir dir)
{
    if (dir.exists()) {
//        QStringList filters;
//        filters << QString("*.jpg") << QString("*.png");
        dir.setFilter(QDir::Files | QDir::NoSymLinks); //设置类型过滤器，只为文件格式
//        dir.setNameFilters(filters);  //设置文件名称过滤器，只为filters格式

        //统计文件个数
        dir_count = dir.count();
        if (dir_count <= 0)
            return;
        QString file;
        QStringList list;

        for (int i = 0; i <= dir_count - 1; i++) {
            file = dir[i];

            list = file.left(file.length() - 4).split("-");
            fileName=dir.absolutePath()+"/"+file;
//                ui->listWidget->resize(120,400);
            ui->listWidget->setViewMode(QListView::IconMode);
            //设置QListWidget中单元项的图片大小
            ui->listWidget->setIconSize(QSize(600,100));
            //设置QListWidget中单元项的间距
            ui->listWidget->setSpacing(10);    //设置自动适应布局调整（Adjust适应，Fixed不适应），默认不适应
            ui->listWidget->setResizeMode(QListWidget::Adjust);    //设置不能移动
            ui->listWidget->setMovement(QListWidget::Static);
            //定义QListWidgetItem对象
//                QListWidgetItem *imageItem = new QListWidgetItem();
            QPixmap *pix=new QPixmap(fileName);//为单元项设置属性
            QListWidgetItem *imageItem = new QListWidgetItem(QIcon(pix->scaled(QSize(600,100))),file);
//                imageItem->setIcon(QIcon(fileName);        //imageItem->setText(tr("Browse"));
            //重新设置单元项图片的宽度和高度
            imageItem->setSizeHint(QSize(100,115));        //将单元项添加到QListWidget中
            ui->listWidget->addItem(imageItem);
            //显示QListWidget
        }
        ui->listWidget->show();
    } else {
        dir.mkpath(".");
    }
}

void DigitalArchiveFrm::on_listWidget_clicked(const QModelIndex &index) {
//    QString page = ui->listWidget->model()->index(ui->listWidget->currentIndex().row(), 0).data().toString().mid(1).remove(-1,1);
    int currow = ui->listWidget->currentRow();
//    ui->lab_page->setText('%1'+"/"+'%2').arg(QString::number(currow)).arg(QString::number(dir_count));
    QImage *fileimage = new QImage();
    if(ui->listWidget->currentItem()!=NULL)
        {
        QString file = ui->listWidget->currentItem()->text();
        fileName= dirpath+ "/"+file;
        qDebug() << fileimage->load(fileName);
        qDebug()<<fileName;
        if (fileimage->load(fileName)) {
            ImgShow(fileimage);
        } else {
            //            ui->graphicsView->scene();
        }
    }
}

void DigitalArchiveFrm::reshow(QString text, QString id) {
    this->show();
    cadre_id = id;
    ui->lineedit_name->setText(text);
    QDir dir("/home/sa/" + text);
    if (dir.exists()) {
        QStringList filters;
        filters << QString("*.jpg") << QString("*.png");
        dir.setFilter(QDir::Files | QDir::NoSymLinks); //设置类型过滤器，只为文件格式
        dir.setNameFilters(filters);  //设置文件名称过滤器，只为filters格式

        //统计jpg格式的文件个数
        int dir_count = dir.count();
        if (dir_count <= 0)
            return;
        QString firstfile = dir[0];
        QStringList list;
        list = firstfile.left(firstfile.length() - 4).split("-");

        //设置类别
        QString cadre_name = list[0];
        QString archive_type = list[1];
        QSqlQuery query("select description from ArchiveClassCode where ClassName = '" + archive_type + "'");
        if (query.exec()) {
            int row = query.record().value(0).toString().toInt();
            ui->tableView->selectRow(row);
        }
        showDirFile(dir.absolutePath()+"/"+archive_type);

        //        QSqlRelationalTableModel model = new QSqlRelationalTableModel();


//        //设置页码
//        ui->listWidget->clear();
//        int page = list[2].toInt();
//        for (int i = 1; i <= page; i++) {

//            ui->listWidget->addItem("第" + QString::number(i) + "页");

//        }
//        ui->listWidget->setCurrentRow(page - 1);
//        qDebug() << "/home/sa/" + text + "/" + firstfile;
//        QImage *fileimage = new QImage();
//        if (fileimage->load("/home/sa/" + text + "/" + firstfile)) {
//            ImgShow(fileimage);
//        }

//    } else {
//        dir.mkpath(".");
//    }

    }
}

void DigitalArchiveFrm::on_btn_topdf_clicked()
{
    QPrinter pic_printer(QPrinter::ScreenResolution);       //设置分辨率
        pic_printer.setPageSize(QPrinter::A4);                  //设置纸张尺寸，默认不设置就是A4
        pic_printer.setOutputFormat(QPrinter::PdfFormat);       //设置输出格式pdf

        //用文件对话框设置输出路径
        QString file_path = QFileDialog::getSaveFileName(this,"Export PDF",QString(),"*.pdf");
        if(!file_path.isEmpty())
        {
            //如果没有写后缀就自动加上
            if(QFileInfo(file_path).suffix().isEmpty())
                file_path.append(".pdf");
            pic_printer.setOutputFileName(file_path);           //设置文件名

            /*****************************************绘制图片*****************************************/
            QDir dir(dirpath);
            if (dir.exists()) {
                dir.setFilter(QDir::Files | QDir::NoSymLinks); //设置类型过滤器，只为文件格式
        //        dir.setNameFilters(filters);  //设置文件名称过滤器，只为filters格式

                //统计jpg格式的文件个数
                int dir_count = dir.count();
                if (dir_count <= 0)
                    return;
                QString file;
                QPainter pic_painter;
                int x=100,y=10;
                for (int i = 0; i <= dir_count - 1; i++)
                {
                    file = dir[i];
                    QPixmap pixmap;
                    QString filename = dirpath+"/"+file;

                    bool isload = pixmap.load(filename,"PNG",Qt::AutoColor);
                    int w[dir_count];
                    int h[dir_count];
                    if(isload)
                        {


                        w[i] = pixmap.width();
                        h[i]=pixmap.height();
                        qDebug()<<"宽："<<w[i]<<"高为："<<h[i];
                        qDebug()<<"绘制点为："<<x<<"   "<<y;
//                        int x[i]=x[i]+width,y[i]=y[i]+height;
                        pic_painter.begin(&pic_printer);
                        //在QPrinter上绘图
//                        QRect rect=pic_painter.viewport();              //获取painter的视口区域
//                        int factor=rect.width()/pixmap.width();         //计算painter视口区域与抓取图片区域的尺寸比例因子
//                        pic_painter.scale(factor*0.8,factor*0.8);       //绘制时按照比例因子放大
                        pic_painter.drawPixmap(x,y,w[i],h[i],pixmap);
                        pic_printer.newPage();


                    }
//                    pic_painter.end();

            }

            /***********************以下可利用QPainter自定义绘图**************************************/
        }
        else{
                QMessageBox::warning(this,tr("Path"),tr("You did not select any file."));
        }
}
        }

